import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution6 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param lists ListNode类ArrayList 
     * @return ListNode类
     */
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        // write code here
        return merge(lists,0,lists.size()-1);
    }
    private ListNode merge(ArrayList<ListNode> lists,int left,int right) {
        if(left < right) {
            int mid = (left + right) / 2;
            ListNode list1 = merge(lists,left,mid);
            ListNode list2 = merge(lists,mid+1,right);
            return mergeSort(list1,list2);
        } else if(left == right) {
            return lists.get(left);
        } else {
            return null;
        }
    }
    private ListNode mergeSort(ListNode list1,ListNode list2) {
        if(list1 == null) {
            return list2;
        }
        if(list2 == null) {
            return list1;
        }
        ListNode cur = new ListNode(0);
        ListNode ret = cur;
        while(list1 != null && list2 != null) {
            if(list1.val < list2.val) {
                cur.next = list1;
                list1 = list1.next;
            } else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        if(list1 != null) {
            cur.next = list1;
        }
        if(list2 != null) {
            cur.next = list2;
        }
        return ret.next;
    }
}